using LiJ.Common.Extention;
using System;
using System.Text;

namespace LiJ.Common.Core.Utils
{
	/// <summary>
	///  唯一数字编码生成静态通用类
	/// </summary>
	public static class NumUtil
	{
		private static readonly long TimeStartTicks;

		private static readonly Random Rnd;

		private static readonly NumGenerator Generator;

		/// <summary>		
		/// 随机数字		
		/// </summary>		
		/// <returns></returns>		
		public static string RandomNum(int length = 4)
		{
			StringBuilder stringBuilder = new StringBuilder(length);
			for (int i = 0; i < length; i++)
			{
				stringBuilder.Append(Rnd.Next(0, 9));
			}
			return stringBuilder.ToString();
		}

		/// <summary>
		/// twitter 的snowflake唯一Id算法(排除机器位)
		/// </summary>
		/// <returns></returns>
		public static long SnowNum()
		{
			return Generator.GetNumWithoutWorker();
		}

		/// <summary>
		///  时间戳数字编号（精度 毫秒
		/// </summary>
		/// <returns></returns>
		public static long TimeMilliNum()
		{
			return (DateTime.UtcNow.Ticks - TimeStartTicks) / 10000;
		}

		/// <summary>
		///  时间戳（秒）+ 主编号的后四位 生成的数字编号
		/// </summary>
		/// <param name="mainNum"></param>
		/// <returns></returns>
		public static long SubTimeNum(long mainNum)
		{
			long num = mainNum % 10000;
			return string.Concat(TimeMilliNum(), num).ToInt64(0);
		}

		static NumUtil()
		{
			DateTime dateTime = new DateTime(2017, 12, 1);
			dateTime = dateTime.ToUniversalTime();
            TimeStartTicks = dateTime.Ticks;
			dateTime = DateTime.Now;
            Rnd = new Random(dateTime.Millisecond);
            Generator = new NumGenerator(0L);
		}
	}
}
